#include <iostream>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <unistd.h>

#include "Comm.hpp"
#define Recty_count 5


void Usage(const std::string &proc)
{
    std::cout << "Usage\n\t" << proc << " serverip serverport" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(socket < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }

    // 发起连接
    struct sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport); 
    // server.sin_addr.s_addr = inet_addr(serverip.c_str());
    inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
    int n = connect(sockfd, CONV(&server), sizeof server);
    if(n < 0)
    {
        std::cerr << "connect error" << std::endl;
        return 2;
    }


    int cnt = 0;
    
    while(true)
    {
        std::string inbuffer;
        std::cout << "Please Entyr# ";
        getline(std::cin, inbuffer);

        ssize_t n = write(sockfd, inbuffer.c_str(), inbuffer.size());
        if(n > 0)
        {
            char buffer[1024];
            ssize_t m = read(sockfd, buffer, sizeof(buffer) - 1);
            if(m > 0)
            {
                buffer[m] = 0;
                std::cout << "Server say: " << buffer << std::endl;
            }
            else
                break;
        }   
        else
            break;
    }

    close(sockfd);
    return 0;
}